<template>
    <el-drawer title="我是标题" :visible.sync="dialogVisible" :with-header="false" class="demand_box" size='960px' @close="resetForm">
        <div class="flexbox flexcolumn height_100" v-loading="loading" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0)">
            <div class="demand_head flexbox flexcenter flexbetween">
                <span class="demand_title">素材库视频</span>
                <span class="icon_btn icon_btn_32" @click="resetForm"><img src="@/assets/img/close_check.svg" alt=""></span>
            </div>
            <div class="demand_center flex" v-infinite-scroll="load" :infinite-scroll-disabled="isload">
                <div class="tk_vd_item" v-for="item in tableData" :key="item.video_id">
                    <div class="tk_vd_top" @click="playVideo(item.preview_url)">
                        <el-checkbox v-model="item.check" :disabled="has_check.length>=getMaxLength" class="tk_vd_check" @click.stop.native="()=>{}" @change="checkVedio(item)"></el-checkbox>
                        <div class="tk_vd_duration">{{secondToTimeStr(item.duration)}}</div>
                        <svg class="tk_vd_play" width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <ellipse opacity="0.4" cx="12" cy="12.5028" rx="12" ry="11.9403" fill="black" />
                            <path d="M17.6367 12.0979C17.9578 12.3326 17.9578 12.8118 17.6367 13.0464L9.93392 18.6756C9.54582 18.9592 8.99994 18.6821 8.99994 18.2014L8.99994 6.94294C8.99994 6.46224 9.54582 6.18506 9.93392 6.46869L17.6367 12.0979Z" fill="white" />
                        </svg>
                        <img class="tk_bg_img" :src="item.video_cover_url" alt="">
                        <img class="tk_bg_video" :src="item.video_cover_url" alt="">
                    </div>
                    <div class="tk_vd_fot">
                        <el-tooltip class="item" effect="dark" content="Top Center 提示文字" placement="top">
                            <div slot="content"><div class="all_text">{{item.file_name}}</div></div>
                            <div class="tk_vd_title">{{item.file_name}}</div>
                        </el-tooltip>
                    </div>
                </div>
            </div>
            <div class="goods_footer flexbox flexcenter flexbetween pl_20 pr_20">
                <div class="gd_text">已选：<span class="blue" :class="{'red':has_check.length>=getMaxLength}">{{has_check.length}}</span>/{{getMaxLength}}</div>
                <div class="flex tk_vd_has">
                    <div class="tk_hasckeck" v-for="(item,index) in has_check" :key="item.video_id">
                        <img src="@/assets/img/mar_close.png" alt="" class="tk_hasckeck_delete" @click="deletCheck(item,index)">
                        <img class="tk_hasckeck_img" :src="item.video_cover_url" alt="">
                    </div>
                </div>
                <div class="tk_vd_btn">
                    <el-button class="el-button-width" size="small" @click="resetForm">关 闭</el-button>
                    <el-button type="primary" class="el-button-width" size="small" @click="addVideo" :loading="Loading_ok">保 存</el-button>
                </div>
            </div>
            <PlayVideo ref="play_ref" />
        </div>
    </el-drawer>
</template>

<script>
import PlayVideo from "@/components/common/PlayVideo";
export default {
    props: ["dataForm"],
    name: "",
    data() {
        return {
            Loading_ok:false,
            loading: false,
            dialogVisible: false,
            isload: false,
            has_more: true,
            queryInfo: {
                // cursor: "",
                advertiser_id: "",
                page:1
                // identity_id: "",
                // identity_type: "",
                // identity_authorized_bc_id: "",
            },
            tableData: [],
            has_check: [],
        };
    },
    created() {},
    computed: {
        getMaxLength() {
            console.log(this.dataForm)
            let list = this.dataForm.creatives_base.creatives_class;
            let num = 0;
            for (let i in list) {
                num += list[i].creatives.length;
            }
            let all = 20 - num;
            return all;
        },
    },
    methods: {
        getData() {
            this.dialogVisible = true;
            this.queryInfo.advertiser_id = this.dataForm.base[0].advertiser_id;
            this.queryInfo.page = 1;
            // this.queryInfo.identity_id = this.dataForm.base[0].identity_id;
            // this.queryInfo.identity_type = this.dataForm.base[0].identity_type;
            // this.queryInfo.identity_authorized_bc_id =
                // this.dataForm.base[0].identity_authorized_bc_id;
                console.log(this.queryInfo.page)
            this.getVideoList();
        },
        //获取商品
        async getVideoList() {
            this.loading = true;
            this.isload = true;
        
            const { data: res } = await this.$http.post(
                this.$tiktokUrl + "launch/TiktokInfo/accVideoList",
                this.queryInfo
            );
            
            if (res.code !== 200) {
                this.isload = false;
                this.loading = false;
                this.$message.error(res.msg);
                return;
            } else {
                this.loading = false;
                this.isload = false;
                let list = res.data.list;
                for (let i in list) {
                    list[i].check = false;
                }
                this.tableData = this.tableData.concat(res.data.list);
            }
        },

        // 下拉加载更多
        load() {
            console.log(this.has_more)
            if (this.has_more == false) {
                this.isload = true;
            } else {
                this.queryInfo.page++;
                this.getVideoList();
            }
        },

        // 秒数转换
        secondToTimeStr(t) {
            if (!t) return;
            t = Math.round(t);
            if (t < 60) return "00:" + ((i = t) < 10 ? "0" + i : i);
            if (t < 3600)
                return (
                    "" +
                    ((a = parseInt(t / 60)) < 10 ? "0" + a : a) +
                    ":" +
                    ((i = t % 60) < 10 ? "0" + i : i)
                );
            if (3600 <= t) {
                var a,
                    i,
                    e = parseInt(t / 3600);
                return (
                    (e < 10 ? "0" + e : e) +
                    ":" +
                    ((a = parseInt((t % 3600) / 60)) < 10 ? "0" + a : a) +
                    ":" +
                    ((i = t % 60) < 10 ? "0" + i : i)
                );
            }
        },

        // 选择视频
        checkVedio(item) {
            this.$forceUpdate();
            if (item.check) {
                this.has_check.push(item);
            } else {
                let index = this.has_check.findIndex(
                    (val) => val.video_id == item.video_id
                );
                this.has_check.splice(index, 1);
            }
        },

        // 删除已选视频
        deletCheck(item, index) {
            this.has_check.splice(index, 1);
            let num = this.tableData.findIndex(
                (val) => val.video_id == item.video_id
            );
            if (num != -1) {
                this.tableData[num].check = false;
            }
        },

       async addVideo() {
        this.Loading_ok = true;
        this.loading = true;
            if (this.has_check.length == 0) {
                this.$message.error("请先选择素材");
                return;
            } else {
                let extractedPaths = (item) => {  
                    const url = item;  
                    // 正则表达式解释：  
                    // 1. ^.*?：非贪婪地匹配从开始到第一个tos-alisg-p-之前的任意字符（但这里我们假设url总是以tos-alisg-p-开始，所以这部分可以省略）  
                    // 2. tos-alisg-p-：匹配字面量tos-alisg-p-  
                    // 3. (.*?)：非贪婪地匹配任意字符，直到遇到后面的模式为止，这部分是我们想要提取的  
                    // 4. (?:~|\.[^\s/]+$)：非捕获组，匹配~或任意不以/开头的字符（即文件扩展名）直到字符串结束  
                    // 注意：这里假设url的格式是固定的，即tos-alisg-p-之后是我们要提取的路径，然后是~或文件扩展名  
                    const regex = /tos-alisg-p-(.*?)(?:~|\.[^\s/]+$)/;  
                    const match = url.match(regex);  
                    return match ? match[1] : null; // 如果找到匹配项，则返回第一个捕获组（即我们要的路径），否则返回null  
                };
                for (let index = 0; index < this.has_check.length; index++) {
                        const { data: res } = await this.$http.get(
                        this.$tiktokUrl + "launch/TiktokInfo/suggestCoverList",{ params:{
                            advertiser_id:this.queryInfo.advertiser_id,
                            video_id:this.has_check[index].video_id
                        }}
                    );
                    if (res.code !== 200) {
                        this.$message.error(res.msg);
                        return;
                    } else {
                        this.has_check[index].video_coverUrl_custom = res.data.list[0].id
                    }
                }
                 

                this.dataForm.creatives_base.creatives_class[
                    this.dataForm.creatives_index
                ].creatives.push.apply(
                    this.dataForm.creatives_base.creatives_class[
                        this.dataForm.creatives_index
                    ].creatives,
                    this.has_check.map(res=>{ return {
                        file_name:res.file_name,
                        video_cover_url:res.video_cover_url,
                        preview_url:res.preview_url,
                        duration:res.duration,
                        video_id:res.video_id,
                        image_ids:[res.video_coverUrl_custom],//[extractedPaths(res.video_cover_url)],
                        ad_text:"",
                        dark_post_status:"OFF"
                    }})
                );
                this.sessionSave();
                this.resetForm();
            }
        },

        // 播放视频
        playVideo(url) {
            this.$refs.play_ref.getData(url);
        },

        // 关闭重置表单
        resetForm() {
            this.Loading_ok = false;
            this.loading = false;
            this.dialogVisible = false;
            this.has_more = false;
            this.has_more = true;
            this.queryInfo.cursor = "";
            this.tableData = [];
            this.has_check = [];
        },

        sessionSave() {
            this.$emit("sessionSave");
        },
    },
    components: {
        PlayVideo,
    },
};
</script>
<style scoped>
.demand_center {
    padding: 20px 0 0 10px;
}
.tk_vd_item {
    width: 215px;
    float: left;
    margin: 0 10px 20px;
}
.tk_vd_top {
    height: 200px;
    position: relative;
    cursor: pointer;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
    overflow: hidden;
}

.tk_bg_img {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    filter: blur(20px);
}

.tk_bg_video {
    display: block;
    margin: 0 auto;
    width: 114px;
    height: 100%;
    position: relative;
    z-index: 2;
}
.tk_vd_play {
    position: absolute;
    z-index: 3;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.tk_vd_duration {
    position: absolute;
    z-index: 3;
    text-shadow: 0px 0px 2px rgba(0, 0, 0, 0.5);
    color: #fff;
    font-size: 13px;
    line-height: 18px;
    right: 63px;
    bottom: 12px;
}
.tk_vd_fot {
    padding: 12px;
    border: 1px solid #ebebeb;
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
}
.tk_vd_title {
    font-size: 13px;
    color: #17233d;
    height: 40px;
    line-height: 20px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}
/deep/ .tk_vd_check {
    position: absolute !important;
    z-index: 3;
    right: 10px;
    top: 10px;
    cursor: pointer;
}
/deep/ .tk_vd_check .el-checkbox__inner {
    width: 18px;
    height: 18px;
    /* background-color: transparent; */
}
/deep/ .tk_vd_check .el-checkbox__inner::after {
    top: 3px;
    left: 6px;
}
/deep/ .tk_vd_check .el-checkbox__input.is-checked .el-checkbox__inner {
    /* background-color: transparent;
    border-color: #fff; */
}
.goods_footer {
    height: 72px;
    border-top: 1px solid #ebebeb;
}
.gd_text {
    font-size: 14px;
    color: #b4b7bd;
    flex-shrink: 0;
}
.tk_vd_btn {
    font-size: 14px;
}
.tk_vd_has {
    margin: 0 10px;
    overflow-x: auto;
    height: 72px;
    white-space: nowrap;
}
.tk_vd_has::-webkit-scrollbar {
    width: 5px;
    height: 5px;
}
.tk_hasckeck {
    width: 28px;
    height: 40px;
    position: relative;
    margin-right: 10px;
    margin-top: 15px;
    display: inline-block;
    border: 1px solid #ebebeb;
}
.tk_hasckeck .tk_hasckeck_img {
    display: block;
    width: 100%;
    height: 100%;
    border-radius: 2px;
}
.tk_hasckeck .tk_hasckeck_delete {
    position: absolute;
    right: -7px;
    top: -7px;
    color: #616c85;
    z-index: 2;
    cursor: pointer;
}
.blue {
    color: #4475ff;
}
.red {
    color: #fe6262;
}
.all_text{
    width: 195px;
    color: #fff;
    font-size: 14px;
}
</style>


